<template>
	<!-- 验收编辑页面 -->
	<view class="main">
		<!-- 商品信息区域 -->
		<view class="info-group name">
			<view class="info-label">品名：</view>
			<view class="name-container">
				<view class="name_item">
					{{ acceptItem.goodName || '未知名称' }}
				</view>
			</view>
		</view>
		
		<view class="info-group spec">
			<text class="info-label">规格：</text>
			<text class="spec-value">{{ acceptItem.spec?.specStr || '未知规格' }}</text>
		</view>

		<!-- 商品图片点击显示区域 -->
		<view class="productPic-container" v-if="product.photo && product.photo.length > 0">
			<view class="productPic-placeholder" @click="showPictures = true">
				<uni-icons type="image" size="40" color="#666"></uni-icons>
				<text class="productPic-text">点击查看商品图片 ({{ product.photo.length }})</text>
			</view>
			
			<!-- 图片轮播弹窗 -->
			<view class="productPic-wrapper" v-if="showPictures">
				<view class="productPic-overlay" @click="showPictures = false"></view>
				<view class="productPic-modal">
					<view class="productPic-close" @click="showPictures = false">
						<uni-icons type="close" size="30" color="#fff"></uni-icons>
					</view>
					<swiper :indicator-dots="true" :autoplay="false" :interval="3000" :duration="1000" :circular="product.photo.length > 1">
						<swiper-item v-for="(pic, index) in product.photo" :key="index">
							<view class="swiper-item">
								<image :src="pic" mode="widthFix" @error="onImgError(index)" class="product-img"></image>
							</view>
						</swiper-item>
					</swiper>
				</view>
			</view>
		</view>
		
		<!-- 无图片时显示占位区域 -->
		<view class="no-pic" v-else>
			<uni-icons type="image" size="60" color="#ccc"></uni-icons>
			<text class="no-pic-text">暂无商品图片</text>
		</view>

		<!-- 验收指令选择 -->
		<view class="batch_order">
			
		</view>
		
		<!-- 数量信息 -->
		<view class="info-group quantity">
			<view class="quantity-item">
				<text class="info-label">申请数量:</text>
				<text>{{ acceptItem.quantity }}{{ acceptItem.unit?.unitName || '' }}</text>
				<text class="quantity-note">(注：)</text>
			</view>
			<view class="check-status">
				<text class="info-label">验收情况：</text>
				<text>{{ acceptItem.CheckDetailId?.[0]?.checkStatus?.label || '未填写' }}</text>
			</view>
		</view>
		
		<scroll-view scroll-y="true" class="scroll" :scroll-with-animation="true">
			<view class="scroll-content">
				<!-- 验收明细区域 -->
				<view class="order_area">
					<view class="order_item">
						<view class="" v-for="(item,index) in selectUnitList" :key="index" >
							<view class="quantity_0" @click="handleCurrentIndex(index)">
								<view class="add no">{{ index + 1 }}</view>
								
								<picker mode="selector" :range="acceptType" :value="getAcceptTypeIndex(index)" 
									@change="selectAcceptType(index,$event)" range-key="title">
									<view class="acceptType" :class="{ acceptType_err:  item.checkType.type !== 'normal' }">{{ item.checkType.title }}</view>
								</picker>
								
								<input 
									class="quantity_input" 
									type="number" 
									v-model="item.quantity" 
									placeholder="数量" 
									@input="handleQuantityInput(index)"
								/>
								
								<picker mode="selector" :range="product.unit" :value="getUnitIndex(index)" 
									range-key="unitName" @change="selectUnit(index, $event)">
									<view class="unitarea">
										<view class=""><input type="text" v-model="item.unitName" /></view>
										<view class=""><uni-icons type="down"></uni-icons></view>
									</view>
								</picker>
								
								<view class="del action-btn" @click.stop="delUnit(index)"><uni-icons type="trash" size="20" color="red"></uni-icons></view>
								<view v-if="index === selectUnitList.length - 1" class="add action-btn" @click.stop="addUnit(index)">+</view>
							</view>
						</view>
						
						<!-- 底部占位元素 -->
						<view class="bottom-spacing"></view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 底部操作按钮 -->
		<view class="btn-group">
			<view class="cancel-btn" @click="close">取消</view>
			<view class="confirm-btn" @click="handleSave">保存修改</view>
		</view>
	</view>
</template>

<script>
const CloudDB = uniCloud.importObject('getDb');
import unitRead from '../../untils/unitRead';
import { acceptType } from '../../untils/acceptType';
import { store } from '../../uni_modules/uni-id-pages/common/store.js';
import getImgUrl from '../../untils/getImgUrl';


export default {
	name: 'checkAcceptEdit',
	props: {
		acceptItem: {
			type: Object,
			required: true,
			default: () => ({})
		},
		// 传入需要编辑的验收记录ID
		checkId: {
			type: String,
			required: true
		}
	},

	data() {
		return {
			editForm: {
				productId: '',
				acceptItemId: '',
				batchInfo: {
					batchName: '',
					batchOrderIndex: 0
				},
				checkStatus: {
					value: '',
					label: ''
				},
				checkTime: 0,
				checkerId: '',
				checkerName: ''
			},
			product: {},
			batchList: [],
			selectUnitList: [],
			acceptType,
			currentIndex: -1,
			showPictures: false
		};
	},

	computed: {
		//计算总数量（转换为基准单位）
		total() {
			return this.selectUnitList.reduce((sum, item) => {
				const relationship = Number(item.unit?.relationship) || 0;
				const quantity = Number(item.quantity) || 0;
				return sum + relationship * quantity;
			}, 0);
		},

		// 按验收类型统计
		totalByType() {
			return this.selectUnitList.reduce((acc, item) => {
				const type = item.checkType?.type;
				const quantity = Number(item.quantity * (item.unit?.relationship || 0)) || 0;

				if (!acc[type]) {
					acc[type] = 0;
				}
				
				acc[type] += quantity;
				return acc;
			}, {});
		}
	},
	
	mounted() {
		this.getProduct();

		// 安全初始化 selectUnitList
		const checkDetail = this.acceptItem.CheckDetailId?.[0] || {};
		this.selectUnitList = checkDetail.checkDetails || [];

	},
	
	methods: {
		// 处理数量输入，确保非负
		handleQuantityInput(index) {
			const value = Number(this.selectUnitList[index].quantity) || 0;
			this.selectUnitList[index].quantity = Math.max(0, value);
		},

		// 单位转换说明
		beforeUnitRead() {
			if (!this.product?.unit || !this.acceptItem.unit?.id) {
				return '';
			}
			return unitRead(this.product.unit, this.acceptItem.unit.id, this.acceptItem.quantity) || '';
		},
 
		// 处理验收类型统计
		getTypeStatistics() {
			if (Object.keys(this.totalByType).length === 0) return [];
			
			const reslist = [];
			const acceptTypeMap = this.acceptType.reduce((map, item) => {
				map[item.type] = item.title;
				return map;
			}, {});

			for (let type of Object.keys(this.totalByType)) {
				if (acceptTypeMap[type] && this.totalByType[type] > 0) {
					reslist.push({
						title: acceptTypeMap[type],
						count: this.totalByType[type]
					});
				}
			}
			
			return reslist;
		},
		
		// 验收情况说明
		checkReadMe() {
			if (!this.product?.unit || this.total <= 0) return '';
			return unitRead(this.product.unit, this.product.unit[0]?.id, this.total) || '';
		},

		// 获取当前单位在列表中的索引
		getUnitIndex(index) {
			const unitId = this.selectUnitList[index].unit?.id;
			return this.product.unit?.findIndex(u => u.id === unitId) || 0;
		},

		// 获取当前验收类型在列表中的索引
		getAcceptTypeIndex(index) {
			const type = this.selectUnitList[index].checkType?.type;
			return this.acceptType.findIndex(t => t.type === type) || 0;
		},

		// 选择单位
		selectUnit(index, e) {
			if (!this.product.unit || !this.product.unit[e.detail.value]) return;
			
			this.selectUnitList[index].unit = this.product.unit[e.detail.value];
			this.selectUnitList[index].unitId = this.product.unit[e.detail.value].id;
			this.selectUnitList[index].unitName = this.product.unit[e.detail.value].unitName;
			this.selectUnitList[index].relationship = this.product.unit[e.detail.value].relationship || 0;
		},
		
		// 设置当前编辑索引
		handleCurrentIndex(index) {
			this.currentIndex = index;
		},
		
		// 关闭页面
		close() {
			this.$emit('close');
		},
		
		// 添加验收单位行
		addUnit() {
			const newUnit = {
				checkType: this.acceptType[0],
				quantity: 0,
				unit: this.product.unit?.[0] || {},
				unitId: this.product.unit?.[0]?.id || '',
				unitName: this.product.unit?.[0]?.unitName || '',
				relationship: this.product.unit?.[0]?.relationship || 1,
				convertedQuantity: 0
			};
			this.selectUnitList.push(newUnit);
			this.currentIndex = this.selectUnitList.length - 1;
		},
		
		// 删除验收单位行
		delUnit(index) {
			if (this.selectUnitList.length <= 1) {
				this.selectUnitList[index].quantity = 0;
				return;
			}
			
			uni.showModal({
				title: '确认删除',
				content: '确定要删除本行验收信息吗？',
				success: (res) => {
					if (res.confirm) {
						this.selectUnitList.splice(index, 1);
						if (this.currentIndex === index) {
							this.currentIndex = Math.max(0, index - 1);
						}
					}
				}
			});
		},
		
		// 选择验收类型
		selectAcceptType(index, e) {
			this.selectUnitList[index].checkType = this.acceptType[e.detail.value];
		},
		
		// 获取商品信息
		async getProduct() {
			if (!this.acceptItem || !this.acceptItem.productId) {
				return;
			}

			try {
				const res = await CloudDB.getDB('product', { _id: this.acceptItem.productId });
				
				if (res.code && res.data && res.data.length) {
					this.product = res.data[0];
					// 处理商品图片
					if (this.product.photo && this.product.photo.length) {
						this.product.photo = await Promise.all(
							this.product.photo.map(item => getImgUrl(item.fileId))
						);
					}
				}
			} catch (e) {
				console.error('获取商品信息失败：', e);
			}
		},
		
		// 选择批次
		handleOrder(idx, val) {
			this.editForm.batchInfo.batchOrderIndex = idx;
			this.editForm.batchInfo.batchName = val;
		},

		// 图片加载失败处理
		onImgError(index) {
			if (this.product.photo && this.product.photo[index]) {
				this.product.photo[index] = '/static/images/default-product.png';
			}
		},

		// 保存修改
		async handleSave() {
			// 前端验证
			if (!this.selectUnitList.some(item => Number(item.quantity) > 0)) {
				return uni.showToast({ title: '请填写验收数量', icon: 'none' });
			}

			// 构建提交数据
			const form = {
				...this.editForm,
				checkDetails: this.selectUnitList
					.filter(item => Number(item.quantity) > 0)
					.map(unit => ({
						checkType: unit.checkType,
						quantity: Number(unit.quantity),
						unitId: unit.unitId,
						unitName: unit.unitName,
						relationship: Number(unit.relationship) || 0,
						convertedQuantity: Number(unit.quantity) * (Number(unit.relationship) || 0)
					})),
				totalQuantity: this.total,
				checkTime: Date.now(),
				checkStatus: this.checkAcceptanceStatus()
			};

			// 调用接口保存
			try {
				uni.showLoading({ title: '保存中...' });
				const res = await CloudDB.updateDB('inventory_check_result', { _id: this.checkId }, form);
				
				if (res.code) {
					uni.showToast({ title: '修改成功', icon: 'success' });
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({ title: res.errMsg || '保存失败', icon: 'none' });
				}
			} catch (err) {
				console.error('保存失败', err);
				uni.showToast({ title: '保存失败，请重试', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},

		// 检查验收状态
		checkAcceptanceStatus() {
			// 检查数量是否少于申请数量
			if (this.total < this.acceptItem.quantity) {
				return {
					value: "quantityLess",
					label: "数量少了"
				};
			}
			
			// 检查数量是否多于申请数量
			if (this.total > this.acceptItem.quantity) {
				return {
					value: "quantityToo",
					label: "数量多了"
				};
			}

			// 收集所有非正常验收类型
			const abnormalTypes = this.selectUnitList
				.filter(item => Number(item.quantity) > 0 && item.checkType.type !== "normal")
				.map(item => item.checkType.title);
			
			// 存在非正常验收类型
			if (abnormalTypes.length > 0) {
				return {
					value: "abnormal",
					label: abnormalTypes.join(',')
				};
			}
			
			// 所有检查都通过
			return {
				value: "normal",
				label: "验收无误"
			};
		}
	}
};
</script>

<style lang="scss" >
	   @import '../../common/variables.scss';
.main {
	width: 100%;
	padding-bottom: 120rpx;
	background-color: $color-bg-light;
	position: relative;
}

// 扫描区域
.scanarea {
	display: flex;
	align-items: center;
	justify-content: space-between;
	width: 100%;
	max-width: 500rpx;
	height: 60rpx;
	margin: 0 auto $gap-base;
	padding: 0 20rpx;
	border: $border-width solid $color-border;
	border-radius: $radius-base;
	background-color: $color-bg-white;
	
	input {
		flex: 1;
		height: 100%;
		font-size: 28rpx;
	}
	
	uni-icons {
		font-size: 32rpx;
		color: $color-primary;
	}
}

// 滚动区域样式
.scroll {
	height: 500rpx;
	width: 100%;
	padding-bottom: 20rpx;
}
.info-group {
	width: 100%;
	padding: 0 $gap-base;
	margin: $gap-sm 0;
	color: $color-text;
	font-size: 28rpx;
	
	.info-label {
		color: $color-text-secondary;
		font-weight: 600;
		margin-right: 10rpx;
	}
}

// 品名样式
.name {
	display: flex;
	flex-wrap: wrap;
	align-items: center;
	padding-top: $gap-sm;
	
	.name-container {
		display: flex;
		flex-wrap: wrap;
		flex: 1;
	}
	
	.name_item {
		display: inline-flex;
		white-space: nowrap;
		padding: 8rpx 16rpx;
		margin: 5rpx;
		background-color: $color-bg-white;
		border-radius: $radius-base;
		border: $border-width solid $color-border;
		font-size: 28rpx;
		color: $color-text;
	}
}

// 规格样式
.spec {
	display: flex;
	align-items: center;
	margin: $gap-sm 0;
	
	.spec-value {
		font-size: 30rpx;
		color: $color-primary;
	}
}
.scroll-content {
	width: 100%;
}

// 商品图片容器（点击显示）
.productPic-container {
	width: 100%;
	margin: $gap-base auto;
}

.productPic-placeholder {
	width: 100%;
	padding: 20rpx 0;
	background-color: #eee;
	border-radius: $radius-base;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 15rpx;
	cursor: pointer;
	transition: background-color 0.2s;
	
	&:active {
		background-color: #ddd;
	}
}

.productPic-text {
	font-size: 28rpx;
	color: $color-text-secondary;
}

// 图片弹窗样式
.productPic-wrapper {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.productPic-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.8);
}

.productPic-modal {
	position: relative;
	width: 90%;
	max-width: 600rpx;
	z-index: 1000;
}

.productPic-close {
	position: absolute;
	top: -50rpx;
	right: 0;
	width: 40rpx;
	height: 40rpx;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

// 商品图片轮播
.swiper-item {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.product-img {
	width: 100%;
	height: auto;
	max-height: 80vh;
	object-fit: contain;
}

// 无图片占位
.no-pic {
	width: 100%;
	height: 0;
	padding-bottom: 50%;
	background-color: #eee;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	color: $color-text-light;
	position: relative;
	
	.no-pic-text {
		margin-top: 20rpx;
		font-size: 26rpx;
	}
}

// 批次选择区
.batch_order {
	display: flex;
	flex-wrap: wrap;
	justify-content: flex-start;
	padding: 0 $gap-base;
	margin: $gap-base 0;
}

.batch_order_item {
	min-width: 120rpx;
	height: 55rpx;
	margin: 10rpx 8rpx;
	padding: 0 15rpx;
	border-radius: $radius-base;
	border: $border-width solid $color-border;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.2s;
	font-size: 26rpx;
	
	&.select {
		background-color: $color-primary;
		color: $color-bg-white;
		border-color: $color-primary;
	}
	
	&:active {
		transform: scale(0.98);
	}
}

// 数量信息区域
.quantity {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	gap: 10rpx;
	padding: $gap-sm $gap-base;
	
	.quantity-item {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		width: 100%;
	}
	
	.check-status {
		display: flex;
		align-items: center;
		width: 100%;
		color: $color-primary;
	}
	
	.quantity-note {
		font-size: 24rpx;
		color: $color-text-light;
		margin-left: 10rpx;
	}
}

// 验收明细区域
.order_area {
	background-color: #dedede;
	margin: $gap-base;
	padding: $gap-base;
	border-radius: $radius-base;
	
	.empty-state {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 200rpx;
		color: $color-text-light;
		font-size: 28rpx;
	}
}

// 数量输入行
.quantity_0 {
	display: flex;
	align-items: center;
	gap: 20rpx;
	width: 100%;
	margin: 20rpx 0;
	padding: 0 10rpx;
}

// 底部占位元素
.bottom-spacing {
	height: $bottom-spacing;
	visibility: hidden;
}

.add.no {
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	background-color: $color-border;
	color: $color-text-secondary;
	font-size: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.acceptType {
	width: 140rpx;
	padding: 10rpx;
	text-align: center;
	border-radius: $radius-base;
	background-color: $color-bg-white;
	border: $border-width solid $color-border;
	color: $color-success;
}

.acceptType_err {
	color: $color-error;
}

.quantity_input {
	width: 150rpx;
	padding: 10rpx 12rpx;
	border-radius: $radius-base;
	border: $border-width solid $color-border;
	background-color: $color-bg-white;
	text-align: right;
}

.unitarea {
	flex: 1;
	min-width: 120rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 60rpx;
	padding: 0 10rpx;
	background-color: $color-bg-white;
	border: $border-width solid $color-border;
	border-radius: $radius-base;
	
	input {
		flex: 1;
		text-align: center;
		background-color: transparent;
	}
	
	uni-icons {
		font-size: 24rpx;
		color: $color-text-light;
	}
}

.action-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 50rpx;
	height: 50rpx;
	border-radius: 50%;
	transition: all 0.2s;
	
	&:active {
		transform: scale(0.9);
	}
}

.add {
	background-color: $color-primary;
	color: $color-bg-white;
	font-size: 36rpx;
	line-height: 40rpx;
}

.del {
	background-color: transparent;
}

// 底部按钮组
.btn-group {
	position: absolute;
	bottom: 0;
	left: 0;
	width: 100%;
	height: 100rpx;
	display: flex;
	background-color: $color-bg-white;
	border-top: $border-width solid $color-border;
	z-index: 10;
	
	.cancel-btn, .confirm-btn {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 500;
	}
	
	.cancel-btn {
		color: $color-text-secondary;
		background-color: #f5f5f5;
		border-right: $border-width solid $color-border;
	}
	
	.confirm-btn {
		color: $color-bg-white;
		background-color: $color-primary;
		transition: background-color 0.2s;
		
		&:active {
			background-color: $color-primary-dark;
		}
	}
}

// 解决picker选择器样式问题
::v-deep .uni-picker {
	height: 60rpx !important;
}
</style>
